<template>
  <view class="documents-container">
    <!-- 头部 -->
    <view class="header">
      <view class="title">📄 文档管理</view>
      <view class="subtitle">上传和管理知识文档</view>
    </view>

    <!-- 统计信息 -->
    <view class="stats-section">
      <view class="stats-item">
        <view class="stats-number">{{ stats.totalDocuments }}</view>
        <view class="stats-label">总文档</view>
      </view>
      <view class="stats-item">
        <view class="stats-number">{{ stats.processedDocuments }}</view>
        <view class="stats-label">已处理</view>
      </view>
      <view class="stats-item">
        <view class="stats-number">{{ stats.totalSize }}</view>
        <view class="stats-label">总大小</view>
      </view>
    </view>

    <!-- 上传区域 -->
    <view class="upload-section">
      <button class="upload-btn" @click="chooseFile">
        <text class="upload-icon">📤</text>
        <text>上传文档</text>
      </button>
      <view class="upload-tips">
        支持 PDF、TXT、DOCX、DOC、MD 格式，最大 50MB
      </view>
    </view>

    <!-- 文档列表 -->
    <view class="documents-list">
      <view class="list-header">
        <text class="list-title">文档列表</text>
        <text class="list-count">共 {{ documents.length }} 个</text>
      </view>

      <view v-if="documents.length === 0" class="empty-state">
        <view class="empty-icon">📁</view>
        <view class="empty-text">暂无文档</view>
        <view class="empty-desc">点击上方按钮上传文档</view>
      </view>

      <view 
        v-for="doc in documents" 
        :key="doc.id"
        class="document-item"
        @click="viewDocument(doc)"
      >
        <view class="doc-icon">📄</view>
        <view class="doc-info">
          <view class="doc-title">{{ doc.title }}</view>
          <view class="doc-meta">
            {{ doc.fileType }} | {{ formatFileSize(doc.fileSize) }} | {{ formatDate(doc.createdAt) }}
          </view>
        </view>
        <view class="doc-actions">
          <view class="doc-status" :class="getStatusClass(doc.status)">
            {{ getStatusText(doc.status) }}
          </view>
          <view class="action-buttons">
            <button 
              v-if="doc.status === 'uploaded'"
              class="action-btn process-btn"
              @click.stop="processDocument(doc.id)"
            >
              处理
            </button>
            <button 
              class="action-btn delete-btn"
              @click.stop="deleteDocument(doc.id)"
            >
              删除
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore" class="load-more">
      <button class="load-more-btn" @click="loadMore" :disabled="loading">
        {{ loading ? '加载中...' : '加载更多' }}
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      documents: [],
      stats: {
        totalDocuments: 0,
        processedDocuments: 0,
        totalSize: '0 MB'
      },
      page: 1,
      size: 10,
      hasMore: true,
      loading: false
    }
  },
  onLoad() {
    this.loadDocuments()
    this.loadStats()
  },
  onShow() {
    this.refreshData()
  },
  onPullDownRefresh() {
    this.refreshData()
  },
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  methods: {
    // 刷新数据
    async refreshData() {
      this.page = 1
      this.hasMore = true
      await Promise.all([
        this.loadDocuments(),
        this.loadStats()
      ])
      uni.stopPullDownRefresh()
    },

    // 加载统计数据
    async loadStats() {
      try {
        const response = await uni.request({
          url: 'https://localhost:7001/api/documents/stats',
          method: 'GET'
        })
        if (response.statusCode === 200) {
          const data = response.data
          this.stats = {
            totalDocuments: data.totalDocuments || 0,
            processedDocuments: data.processedDocuments || 0,
            totalSize: this.formatFileSize(data.totalFileSize || 0)
          }
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    },

    // 加载文档列表
    async loadDocuments() {
      if (this.loading) return
      this.loading = true

      try {
        const response = await uni.request({
          url: 'https://localhost:7001/api/documents',
          method: 'GET',
          data: {
            page: this.page,
            size: this.size
          }
        })
        
        if (response.statusCode === 200) {
          const data = response.data
          const newDocuments = data.items || []
          
          if (this.page === 1) {
            this.documents = newDocuments
          } else {
            this.documents = [...this.documents, ...newDocuments]
          }
          
          this.hasMore = newDocuments.length === this.size
        }
      } catch (error) {
        console.error('加载文档列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 加载更多
    async loadMore() {
      if (this.hasMore && !this.loading) {
        this.page++
        await this.loadDocuments()
      }
    },

    // 选择文件
    chooseFile() {
      uni.chooseFile({
        count: 1,
        type: 'file',
        extension: ['.pdf', '.txt', '.docx', '.doc', '.md'],
        success: (res) => {
          const file = res.tempFiles[0]
          this.uploadFile(file)
        },
        fail: (error) => {
          uni.showToast({
            title: '选择文件失败',
            icon: 'none'
          })
        }
      })
    },

    // 上传文件
    async uploadFile(file) {
      uni.showLoading({
        title: '上传中...'
      })

      try {
        const response = await uni.uploadFile({
          url: 'https://localhost:7001/api/documents/upload',
          filePath: file.path,
          name: 'file',
          formData: {
            fileName: file.name
          }
        })

        if (response.statusCode === 200) {
          uni.showToast({
            title: '上传成功',
            icon: 'success'
          })
          this.refreshData()
        } else {
          throw new Error('上传失败')
        }
      } catch (error) {
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 处理文档
    async processDocument(id) {
      uni.showLoading({
        title: '处理中...'
      })

      try {
        const response = await uni.request({
          url: `https://localhost:7001/api/documents/process/${id}`,
          method: 'POST'
        })

        if (response.statusCode === 200) {
          uni.showToast({
            title: '处理已启动',
            icon: 'success'
          })
          this.refreshData()
        } else {
          throw new Error('处理失败')
        }
      } catch (error) {
        uni.showToast({
          title: '处理失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 删除文档
    deleteDocument(id) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个文档吗？删除后无法恢复。',
        success: async (res) => {
          if (res.confirm) {
            try {
              const response = await uni.request({
                url: `https://localhost:7001/api/documents/${id}`,
                method: 'DELETE'
              })

              if (response.statusCode === 200) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                this.refreshData()
              } else {
                throw new Error('删除失败')
              }
            } catch (error) {
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },

    // 查看文档详情
    viewDocument(doc) {
      uni.navigateTo({
        url: `/pages/documents/detail?id=${doc.id}`
      })
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString)
      return date.toLocaleDateString()
    },

    // 获取状态样式类
    getStatusClass(status) {
      const statusMap = {
        'uploaded': 'status-uploaded',
        'processing': 'status-processing',
        'completed': 'status-completed',
        'failed': 'status-failed'
      }
      return statusMap[status] || 'status-uploaded'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'uploaded': '已上传',
        'processing': '处理中',
        'completed': '已完成',
        'failed': '失败'
      }
      return statusMap[status] || status
    }
  }
}
</script>

<style scoped>
.documents-container {
  padding: 20rpx;
  background: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  padding: 40rpx 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20rpx;
  margin-bottom: 30rpx;
  color: white;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.subtitle {
  font-size: 24rpx;
  opacity: 0.9;
}

.stats-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30rpx;
}

.stats-item {
  background: white;
  border-radius: 15rpx;
  padding: 20rpx;
  text-align: center;
  flex: 1;
  margin: 0 10rpx;
}

.stats-number {
  font-size: 32rpx;
  font-weight: bold;
  color: #667eea;
}

.stats-label {
  font-size: 22rpx;
  color: #666;
  margin-top: 5rpx;
}

.upload-section {
  background: white;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  text-align: center;
}

.upload-btn {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 25rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20rpx;
}

.upload-icon {
  margin-right: 10rpx;
  font-size: 32rpx;
}

.upload-tips {
  font-size: 24rpx;
  color: #999;
}

.documents-list {
  background: white;
  border-radius: 15rpx;
  padding: 30rpx;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.list-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.list-count {
  font-size: 24rpx;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.empty-desc {
  font-size: 24rpx;
  color: #999;
}

.document-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.document-item:last-child {
  border-bottom: none;
}

.doc-icon {
  font-size: 40rpx;
  margin-right: 20rpx;
}

.doc-info {
  flex: 1;
}

.doc-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 5rpx;
}

.doc-meta {
  font-size: 22rpx;
  color: #999;
}

.doc-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10rpx;
}

.doc-status {
  padding: 5rpx 10rpx;
  border-radius: 15rpx;
  font-size: 20rpx;
}

.status-uploaded {
  background: #e3f2fd;
  color: #1976d2;
}

.status-processing {
  background: #fff3e0;
  color: #f57c00;
}

.status-completed {
  background: #e8f5e8;
  color: #388e3c;
}

.status-failed {
  background: #ffebee;
  color: #d32f2f;
}

.action-buttons {
  display: flex;
  gap: 10rpx;
}

.action-btn {
  padding: 8rpx 16rpx;
  border-radius: 10rpx;
  font-size: 22rpx;
  border: none;
}

.process-btn {
  background: #38a169;
  color: white;
}

.delete-btn {
  background: #e53e3e;
  color: white;
}

.load-more {
  text-align: center;
  padding: 30rpx 0;
}

.load-more-btn {
  background: #f8f9fa;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
  color: #666;
}

.load-more-btn:disabled {
  background: #f5f5f5;
  color: #ccc;
}
</style> 